package deng.qiya.everplay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.net.Uri;
import android.util.Log;
import android.util.Xml;

public class DownloadService {
	
	
	public PlayResourcesConfigure getRemoteResConfig(String path) throws Exception{
		PlayResourcesConfigure resCfg = null;
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(3000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream is = conn.getInputStream();
			resCfg = xmlParser(is);
			return resCfg;
		} else {
			return null;
		}
	}
	
	private PlayResourcesConfigure xmlParser(InputStream is) throws XmlPullParserException, IOException{
		PlayResourcesConfigure resCfg = new PlayResourcesConfigure();
		List<PlayResource> list = null;
		PlayResource playRes = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is,"utf-8");
		int eventType = parser.getEventType();
		while((eventType=parser.next())!=XmlPullParser.END_DOCUMENT){
			switch (eventType) {
			case XmlPullParser.START_TAG:
				if("resources".equalsIgnoreCase(parser.getName())){
					list = new ArrayList<PlayResource>();
				}
				else if("resource".equalsIgnoreCase(parser.getName())){
					playRes = new PlayResource();
					playRes.setTitle(parser.getAttributeValue("", "title"));
					playRes.setDescription(parser.getAttributeValue("", "description"));
					playRes.setType(parser.getAttributeValue("", "type"));
					playRes.setName(parser.getAttributeValue("", "name"));
				}
				else if("EverPlay".equalsIgnoreCase(parser.getName())){
					resCfg.setPlayTime(Integer.valueOf(parser.getAttributeValue("", "playTime")));
				}
				break;

			case XmlPullParser.END_TAG:
				if("resources".equalsIgnoreCase(parser.getName())){
					resCfg.setList(list);
				}
				else if ("resource".equalsIgnoreCase(parser.getName())){
					list.add(playRes);
				}
				break;
			default:
				break;
			}
		}
		return resCfg;
	}
	
	public Uri getImageURI(String urlStr, File everPlayPath) throws Exception {
		String name = getMD5(urlStr) + urlStr.substring(urlStr.lastIndexOf("."));
		Log.d("download Image", "download url:"+urlStr +"\nsave path"+ everPlayPath.getPath());
		File file = new File(everPlayPath, name);
		
		if (file.exists()) {
			return Uri.fromFile(file);
		} else {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			if (conn.getResponseCode() == 200) {

				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
				}
				is.close();
				fos.close();
				return Uri.fromFile(file);
			}
		}
		return null;
	}
	
	public static String getMD5(String content) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(content.getBytes());
			return getHashString(digest);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }
    
    //download all resource by resCfg;
    public void downloadAllResourceByResCfg(PlayResourcesConfigure resCfg, File everPlayPath) {
    	List<PlayResource> list = resCfg.getList();
    	for(int i =0; i< list.size(); i++){
    		String url = Constant.RESOURCE_PATH + resCfg.getList().get(i).getName();
    		Log.d("urlurl", url);
    		Log.d("paht", everPlayPath.getPath());
    		try {
				getImageURI(url, everPlayPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }
    
    
}
